package com.ljq.controller;

import com.alibaba.fastjson.JSON;
import com.ljq.pojo.Actor;
import com.ljq.pojo.Movie;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class TestController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    //判断 索引是否存在
    @RequestMapping("testExistIndex")
    @ResponseBody
    public void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("movie_index");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
    //删除 索引
    @RequestMapping("delete")
    @ResponseBody
    public String delete() throws IOException {
        // 操作索引的对象
        IndicesClient indices = restHighLevelClient.indices();
        // 删除索引的请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("movie_index");
        // 删除索引
        AcknowledgedResponse delete = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT);
        // 得到响应
        // 删除索引

        // 得到响应
        boolean b = delete.isAcknowledged();
        System.out.println(b);
        return "ok";
    }
    //增加
    @RequestMapping("add")
    @ResponseBody
    public String add() throws IOException {
        List<Actor> actorList = Arrays.asList(new Actor(1, "彭于晏1"), new Actor(2, "谢霆锋1"));
        Movie movie = new Movie(6, "古惑仔20201", 8.8, actorList);
        // 请求对象 指定索引名称，和source 数据  //将我们的数据放入请求json
        IndexRequest indexRequest = new IndexRequest("movie_index").source(JSON.toJSONString(movie), XContentType.JSON);
        // 执行得到 response
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("出参：" + indexResponse.toString());
        return "ok";

    }
    // 修改
    @RequestMapping("update")
    @ResponseBody
    public String update() throws IOException {
        List<Actor> actorList = Arrays.asList(new Actor(1, "周星驰"), new Actor(2, "周润发"));
        Movie movie = new Movie(6, "赌神", 9.9, actorList);
        // 请求对象 指定索引名称，和source 数据  //将我们的数据放入请求json
        UpdateRequest updateRequest = new UpdateRequest("movie_index","4JM7U4IBy7vHw2EMhyDc");
        updateRequest.doc(JSON.toJSONString(movie),XContentType.JSON);
        // 执行得到 response
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("出参：" + update.toString());
        return "ok";

    }
    //根据id获取
    @RequestMapping("getInfo")
    @ResponseBody
    public String get() throws IOException {
        GetRequest getRequest = new GetRequest("movie_index", "4JM7U4IBy7vHw2EMhyDc");
        // 查询结果
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        String id = documentFields.getId();// id
        Map<String, DocumentField> fields = documentFields.getFields();
        String index = documentFields.getIndex();// index
        Map<String, Object> source = documentFields.getSource();// 索引的字段信息
        long primaryTerm = documentFields.getPrimaryTerm();
        long version = documentFields.getVersion();
        Map<String, Object> source1 = documentFields.getSource();
        System.out.println(source1);
        System.out.println("id:" + id + "index:" + index + "version:" + version + "count:" + fields.size());
        return "ok";

    }

    //删除文档记录
    @RequestMapping("testDeleteRequest")
    @ResponseBody
    public void testDeleteRequest() throws IOException{
        DeleteRequest request = new DeleteRequest("movie_index","4JM7U4IBy7vHw2EMhyDc");
        request.timeout("1s");
        DeleteResponse deleteResponse = restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }
    //获取某个索引下所有数据
    @RequestMapping("getAll")
    @ResponseBody
    public String getAll() throws IOException, ParseException {
        // 搜索请求对象
        SearchRequest searchRequest = new SearchRequest("movie_index");
        // 搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 搜索方式
        // matchAllQuery搜索全部
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        // 设置源字段过虑,第一个参数结果集包括哪些字段，第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name", "doubanScore", "actorList"}, new String[]{});
        // 向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        // 执行搜索,向ES发起http请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 搜索结果
        SearchHits hits = searchResponse.getHits();
        Arrays.stream(hits.getHits()).iterator().forEachRemaining(e -> {
            System.out.println(e);
        });
        return "ok";
    }

    //分页查询
    @RequestMapping("findAllPage")
    @ResponseBody
    public String findAllPage() throws IOException {
        // 搜索请求对象
        SearchRequest searchRequest = new SearchRequest("movie_index");
        // 搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        int page = 1; // 页码
        int size = 2; // 每页显示的条数
        int index = (page - 1) * size;
        searchSourceBuilder.from(index);
        searchSourceBuilder.size(1);
        // 搜索方式
        // matchAllQuery搜索全部
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        // 设置源字段过虑,第一个参数结果集包括哪些字段，第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name", "doubanScore", "actorList"}, new String[]{});
        // 向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        // 执行搜索,向ES发起http请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 搜索结果
        SearchHits hits = searchResponse.getHits();
        Arrays.stream(hits.getHits()).iterator().forEachRemaining(e -> {
            System.out.println(e);
        });
        return "ok";
    }
    // Query-match单字段模糊查询
    @RequestMapping("queryMatch")
    @ResponseBody
    public String queryMatch() throws IOException {
        // 搜索请求对象
        SearchRequest searchRequest = new SearchRequest("movie_index");
        // 搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        int page = 1; // 页码
        int size = 10; // 每页显示的条数
        int index = (page - 1) * size;
        searchSourceBuilder.from(index);
        searchSourceBuilder.size(2);
        // 搜索方式
        // Query-match单字段模糊查询
        searchSourceBuilder.query( QueryBuilders.matchQuery("name", "古惑仔"));
        // 设置源字段过虑,第一个参数结果集包括哪些字段，第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name", "doubanScore", "actorList"}, new String[]{});
        // 向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        // 执行搜索,向ES发起http请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 搜索结果
        SearchHits hits = searchResponse.getHits();
        Arrays.stream(hits.getHits()).iterator().forEachRemaining(e -> {
            System.out.println(e);
        });
        return "ok";
    }
}
